package fr.flambycrew.domain.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

public abstract class GenericDAO<T> {	

	abstract Class<T> getPersistedClass(); 

	private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("flambycrew-crawler");

	EntityManager createEntityManager() {
		return emf.createEntityManager();
	}

	void closeEntityManager() {
		emf.close();
	}
	
	public void persist(T entity) {
		EntityManager em = createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();

		em.persist(entity);

		tx.commit();
		em.close();
	}
	
	public void merge(T entity){
		EntityManager em = createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();

		em.merge(entity);

		tx.commit();
		em.close();
	}

	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		EntityManager em = createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();

		Query allEntitiesQuery = em.createQuery("select d from " + getPersistedClass().getSimpleName() + " d");

		List<T> allEntities = allEntitiesQuery.getResultList();

		tx.commit();
		em.close();

		return allEntities;
	}

}
